<?php
App::uses('Sanitize','Utility');
class BrandsController extends AppController {
	var $uses = array('Brand');
    public function index() {
		$conditions = array();
		$name = $description = '';
		if($this->request->is('get')){						
			if(!empty($this->params->query['name'])){
				$name = Sanitize::escape($this->params->query['name']);
				$conditions['and']['name like'] = "%$name%";
			}			
			if(!empty($this->params->query['description'])){
				$description = Sanitize::escape($this->params->query['description']);
				$conditions['and']['description like'] = "%$description%";
			}
		}
		$this->paginate = array(
			'limit'=>10,
			'conditions'=>$conditions,
			'order'=>'orderby asc',
		);
        $rs = $this->paginate('Brand');
		$this->set(compact('rs','name','description'));
		if($this->request->is('ajax')){
			$this->layout = 'ajax';
			$this->render('ajax_search');
		}
    }
	
	public function add() {
        if ($this->request->is('post')) {
            $this->Brand->create();
			$orderby = $this->Brand->field('max(orderby)+1');
			if(!$orderby){				
				$orderby = 1;
			}
			$this->request->data['Brand']['orderby'] = $orderby;
            if ($this->Brand->save($this->data,true)) {
                $this->Session->setFlash(__('Đã được lưu'));
                $this->redirect(array('action' => '.'));
            } else {
                $this->Session->setFlash(__('Có lỗi, không lưu được, xin thử lại'));
            }
        }
    }

    public function edit($id = null) {
        $this->Brand->id = $id;
        if (!$this->Brand->exists()) {
            throw new NotFoundException(__('Không tìm thấy'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Brand->save($this->data,true)) {
                $this->Session->setFlash(__('Đã được lưu'));
                $this->redirect(array('action' => '.'));
            } else {
                $this->Session->setFlash(__('Có lỗi, không lưu được, xin thử lại'));
            }
        } else {
            $this->request->data = $this->Brand->read(null, $id);            
        }
    }

    public function delete($id = null) {
		if($id==null) die("No ID received");		
		if($this->Brand->delete($id)==false){
			$this->Session->setFlash('Bị lỗi không xóa được');
		}
		else {
			$this->Session->setFlash('Item đã được xóa khỏi danh sách');
		}
		$this->redirect(array('action'=>'index'));
    }
	
	public function changeorder($id, $change = 'up', $num = 0){
		$tmp = $this->Brand->find('first',array(
			'fields' => array('id','orderby'),
			'conditions' => array(
				'orderby '.($change=='up'?'<':'>') => $num,
			),
			'limit' => 1,
			'order' => 'orderby asc',
		));
		if($tmp){
			$this->Brand->id = $tmp['Brand']['id'];
			$this->Brand->saveField('orderby',$num);
			
			$this->Brand->id = $id;
			$this->Brand->saveField('orderby',$tmp['Brand']['orderby']);
		}
		$this->redirect('.');
	}	
}
